import {Component, Input, OnChanges, OnInit, ViewChild, SimpleChanges} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {EquipMainDataHttpServices} from '../http/http';
import {HttpErrorResponse} from '@angular/common/http';

interface AttrTypeTableItem {
  code: string;
  name: string;
  typeDesc: string;
  unitCode: string;
  dataType: string;
  createUserName: string;
  createTime: string;
  id: number;
}


@Component({
  selector: 'attr-type-form',
  styleUrls: ['./components.less'],
  template: `
    <form nz-form [formGroup]="attrTypeMgmtForm" class="attr-type-form">
      <nz-form-item>
        <nz-form-label nzRequired [nzSpan]="8">
          编码
        </nz-form-label>
        <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
          <input nz-input formControlName="code"/>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label nzRequired [nzSpan]="8">
          名称
        </nz-form-label>
        <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
          <input nz-input formControlName="name"/>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label nzRequired [nzSpan]="8">
          属性类型描述
        </nz-form-label>
        <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
          <input nz-input formControlName="typeDesc"/>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label nzRequired [nzSpan]="8">
          单位
        </nz-form-label>
        <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
          <nz-select formControlName="unitId" *ngIf="selectUnitData">
            <nz-option [nzLabel]="s.code" [nzValue]="s.id" *ngFor="let s of selectUnitData"></nz-option>
          </nz-select>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label nzRequired [nzSpan]="8">
          数据类型
        </nz-form-label>
        <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
          <nz-select formControlName="dataType">
            <nz-option nzLabel="Number" nzValue="Number"></nz-option>
            <nz-option nzLabel="String" nzValue="String"></nz-option>
            <nz-option nzLabel="Double" nzValue="Double"></nz-option>
          </nz-select>
        </nz-form-control>
      </nz-form-item>
    </form>
  `
})

export class AttrTypeFormComponent implements OnChanges, OnInit {

  @Input() mode: string;
  @Input() editData: AttrTypeTableItem;
  @Input() attrTypeMgmtForm!: FormGroup;

  constructor(private fb: FormBuilder, private http: EquipMainDataHttpServices) {
  }

  selectUnitData: any;

  onCreate(successCallback): void {
    if (this.attrTypeMgmtForm.valid) {
      const {code, typeDesc, dataType, unitId, name} = this.attrTypeMgmtForm.value;
      this.http.createType({code, name, typeDesc, dataType, unitId}).subscribe((res) => {
        if (res.code === 0) {
          successCallback();
        }
      }, (err: HttpErrorResponse) => {
      });
    }
  }

  onUpdate(successCallback): void {
    this.http.updateType({...this.attrTypeMgmtForm.value, id: this.editData.id})
      .subscribe((res) => {
        if (res.code === 0) {
          successCallback();
        }
      }, (err: HttpErrorResponse) => {
      });
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (this.mode !== 'create' && this.editData && this.attrTypeMgmtForm) {
      this.attrTypeMgmtForm.patchValue(this.editData);
    }
  }

  ngOnInit(): void {
    this.http.getAllUnit().subscribe((res) => {
        if (res.code === 0) {
          this.selectUnitData = res.data;
        }
      },
      (err: HttpErrorResponse) => {
      });
  }
}


@Component({
  selector: 'app-equip-attr-type-mgmt',
  styleUrls: ['./components.less'],
  template: `
    <div class="equipMainDataMgmtContainer">
      <div class="equip-main-data-mgmt-bar">
        <div><span>单位码：</span><input nz-input placeholder="输入类型编码查询" [(ngModel)]="keyword" /></div>
        <button nz-button nzType="primary" (click)="loadTable()">查询</button>
        <button nz-button style="background:'green';color:'#ffffff';border-color:'transparent'" (click)="visibleObject.toForm = true">新增
        </button>
      </div>
      <nz-table #attrTypeTable nzSize="middle" [nzShowSizeChanger]="true" [nzShowQuickJumper]="true"
                [nzData]="tableData" [nzLoading]="loading" [nzFrontPagination]="false"
                [nzTotal]="pagination.total" [(nzPageSize)]="pagination.size" [(nzPageIndex)]="pagination.start"
                (nzPageIndexChange)="onPageIndexChange($event)" (nzPageSizeChange)="onPageSizeChange($event)">
        <thead>
        <tr>
          <th>类型编码</th>
          <th>类型名称</th>
          <th>类型描述</th>
          <th>单位</th>
          <th>数据类型</th>
          <th>创建人</th>
          <th>创建时间</th>
          <th nzAlign="center">操作</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let data of attrTypeTable.data">
          <td>{{ data.code }}</td>
          <td>{{ data.name }}</td>
          <td>{{ data.typeDesc }}</td>
          <td>{{ data.unitCode }}</td>
          <td>{{ data.dataType }}</td>
          <td>{{ data.createUserName }}</td>
          <td>{{ data.createTime }}</td>
          <td class='option-td' nzAlign="center">
            <span (click)="onEdit(data)">修改</span>
            <span (click)="visibleObject.toDelete = true; deleteId = data.id">删除</span>
          </td>
        </tr>
        </tbody>
      </nz-table>
    </div>

    <nz-modal [(nzVisible)]="visibleObject.toForm" [nzTitle]="modalTitle" (nzOnCancel)="onCancel()"
              (nzOnOk)="onSubmit()" [nzWidth]="744">
      <ng-template #modalTitle>新增属性类型</ng-template>
      <ng-container *nzModalContent>
        <attr-type-form #myForm [mode]="mode" [editData]="editData" [attrTypeMgmtForm]="AttrTypeMgmtForm"></attr-type-form>
      </ng-container>
    </nz-modal>

    <nz-modal [(nzVisible)]="visibleObject.toDelete" nzTitle="警告" (nzOnCancel)="visibleObject.toDelete=false" (nzOnOk)="onDelete()">
      <ng-container *nzModalContent>
        您确认要删除此项吗？
      </ng-container>
    </nz-modal>
  `
})
export class AttrTypeMgmtComponent implements OnInit {
  constructor(private http: EquipMainDataHttpServices, private fb: FormBuilder) {
  }

  @ViewChild('myForm') formComponent;
  AttrTypeMgmtForm!: FormGroup;
  mode = 'create';
  tableData!: Array<AttrTypeTableItem>;
  editData!: AttrTypeTableItem;
  visibleObject: any = {
    toForm: false,
    toDelete: false
  };
  loading = true;
  keyword = '';
  deleteId: any;
  pagination: any = {
    size: 10,
    start: 1,
    total: undefined,
  };


  loadTable(): void {
    const {start, size} = this.pagination;
    this.http.queryType({start: start - 1, size, keyword: this.keyword}).subscribe(
      (res) => {
        if (res.code === 0) {
          this.tableData = res.data.content;
          this.pagination.total = res.data.totalElements;
          this.loading = false;
        }
      }, (err: HttpErrorResponse) => {
        this.loading = false;
        this.tableData = [];
      });
  }

  onSubmit(): void {
    if (this.mode === 'create') {
      this.formComponent.onCreate(() => {
        this.loadTable();
        this.AttrTypeMgmtForm.reset();
      });
    } else {
      this.formComponent.onUpdate(() => {
        this.loadTable();
        this.mode = 'create';
        this.AttrTypeMgmtForm.reset();
      });
    }

    this.visibleObject.toForm = false;
  }


  onCancel(): void {
    this.visibleObject.toForm = false;
    this.mode = 'create';
    this.AttrTypeMgmtForm.reset();
  }

  onEdit(data): void {
    this.visibleObject.toForm = true;
    this.mode = 'edit';
    this.editData = data;
  }

  onDelete(): void {
    this.visibleObject.toDelete = false;
    this.http.deleteType(this.deleteId).subscribe(
      (res) => {
        if (res.code === 0) {
          this.loadTable();
        }
      }, (err: HttpErrorResponse) => {
      });
  }

  onPageIndexChange(data): void {
    this.pagination.start = data;
    this.loadTable();
  }

  onPageSizeChange(data): void {
    this.pagination.size = data;
    this.loadTable();
  }

  ngOnInit(): void {
    this.loadTable();
    this.AttrTypeMgmtForm = this.fb.group({
      code: [null, Validators.required],
      typeDesc: [null, Validators.required],
      name: [null, Validators.required],
      dataType: [null, Validators.required],
      unitId: [null, Validators.required],
    });
  }

}
